package com.isoft.c2team3service2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.c2team3service2.entity.User;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.entity.UserFollowUser;
import com.isoft.c2team3service2.mapper.UserFollowUserMapper;
import com.isoft.c2team3service2.mapper.UserMapper; // 假设存在用户Mapper
import com.isoft.c2team3service2.service.UserFollowUserService;
import com.isoft.c2team3service2.util.UserHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserFollowUserServiceImpl extends ServiceImpl<UserFollowUserMapper, UserFollowUser> implements UserFollowUserService {

    private static final Logger log = LoggerFactory.getLogger(UserFollowUserServiceImpl.class);

    @Autowired
    private UserFollowUserMapper userFollowUserMapper;

    @Autowired
    private UserMapper userMapper; // 用于查询用户信息

    @Override
    @Transactional
    public boolean followUser(Integer followedUserId) {
        // 获取当前用户ID
        Integer userId = UserHolder.getUser().getId();

        // 1. 不能关注自己
        if (userId.equals(followedUserId)) {
            throw new BusinessException("不能关注自己");
        }

        // 2. 检查是否已经关注
        int followCount = userFollowUserMapper.checkFollowStatus(userId, followedUserId);
        if (followCount > 0) {
            throw new BusinessException("您已关注该用户");
        }

        // 3. 添加关注记录
        UserFollowUser follow = new UserFollowUser();
        follow.setUserId(userId);
        follow.setFollowedUserId(followedUserId);
        follow.setCreateTime(LocalDateTime.now());

        try {
            int inserted = userFollowUserMapper.insert(follow);
            return inserted > 0;
        } catch (DuplicateKeyException e) {
            // 捕获数据库的重复键异常，防止高并发下检查失效的情况
            throw new BusinessException("您已关注该用户");
        }
    }

    @Override
    @Transactional
    public boolean unfollowUser(Integer followedUserId) {
        // 获取当前用户ID
        Integer userId = UserHolder.getUser().getId();

        // 删除关注记录
        LambdaQueryWrapper<UserFollowUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFollowUser::getUserId, userId)
                .eq(UserFollowUser::getFollowedUserId, followedUserId);
        return userFollowUserMapper.delete(wrapper) > 0;
    }

    @Override
    public boolean isFollowingUser(Integer followedUserId) {
        // 获取当前用户ID
        Integer userId = UserHolder.getUser().getId();

        // 检查关注状态
        return userFollowUserMapper.checkFollowStatus(userId, followedUserId) > 0;
    }

    @Override
    public List<UserDTO> getFollowedUsers() {
        // 获取当前用户ID
        Integer userId = UserHolder.getUser().getId();
        log.info("当前用户ID：{}", userId);

        // 获取关注的用户ID列表
        List<Integer> followedUserIds = userFollowUserMapper.selectFollowedUserIds(userId);
        log.info("关注的用户ID列表：{}", followedUserIds); // 看是否有值

        // 查询关注的用户信息
        if (followedUserIds.isEmpty()) {
            return List.of();
        }

        // 使用selectBatchIds查询用户信息并转换为UserDTO
        List<User> users = userMapper.selectBatchIds(followedUserIds);
        log.info("根据ID列表查询到的User数量：{}", users.size()); // 看是否与followedUserIds.size()一致

        List<UserDTO> userDTOS = users.stream().map(this::convertToUserDTO).collect(Collectors.toList());
        log.info("转换后的UserDTO数量：{}", userDTOS.size());

        return userDTOS;
    }

    @Override
    public List<UserDTO> getFans() {
        // 获取当前用户ID
        Integer userId = UserHolder.getUser().getId();
        log.info("当前用户ID：{}", userId);

        // 获取粉丝ID列表
        List<Integer> fanUserIds = userFollowUserMapper.selectFanUserIds(userId);
        log.info("粉丝ID列表：{}", fanUserIds);

        // 查询粉丝信息
        if (fanUserIds.isEmpty()) {
            return List.of();
        }

        // 使用selectBatchIds查询用户信息并转换为UserDTO
        List<User> users = userMapper.selectBatchIds(fanUserIds);
        log.info("根据ID列表查询到的User数量：{}", users.size());

        List<UserDTO> userDTOS = users.stream().map(this::convertToUserDTO).collect(Collectors.toList());
        log.info("转换后的UserDTO数量：{}", userDTOS.size());

        return userDTOS;
    }

    /**
     * 将User对象转换为UserDTO对象
     * @param user User对象
     * @return UserDTO对象
     */
    private UserDTO convertToUserDTO(User user) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        return userDTO;
    }
}